﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetfractionHub.LocalMachine.BotCommands;
using NetfractionHub.Network.Protocol;
using NetfractionHub.Network.Protocol.BASE.Factory;
using NetfractionHub.Network.Protocol.UCMD;
using NetfractionHub.Network.Protocol.UCMD.Factory;

namespace AnnouncerBot.Handlers
{
	[CommandHandler("listreleases")]
	[UserCommand("List Releases", FactoryCMD.ConextTypesEnum.HubCommand, "HMSG {0}listreleases\\\\s%[line:Number of releases to list (blank for all releases)]\n")]
	public class ListReleases : CommandHandler
	{
		public override BotReturnStatus HandleCommandMessage(NetfractionHub.RemoteMachine.Node source, CommandMessage message)
		{
			string lastXReleases = "-1";
			if (message.UnnamedArguments.Count == 1)
			{
				int numReleases;
				if (int.TryParse(message.UnnamedArguments[0], out numReleases))
					lastXReleases = message.UnnamedArguments[0];
			}

			Community.CsharpSqlite.SQLiteClient.SqliteDataReader sdr = AnnouncerBot.DataStore.ExecuteQuery("SELECT Users.Username AS AddedBy, Date, Time, Categories.Name AS Category, Magnet FROM Entries JOIN Users ON Entries.AddedBy=Users.UserId JOIN Categories ON Entries.CategoryId=Categories.CategoryId ORDER BY Entries.Date DESC, Entries.Time DESC LIMIT " + lastXReleases);
			if (sdr != null)
			{
				string user, date, time, category, magnet;
				StringBuilder sb = new StringBuilder();
				sb.AppendLine("All releases in the database (<Added By> [Time Added] [Category] - Magnet Link)");
				sb.AppendLine("Use '!listreleases x' to show the last x releases e.g. !listreleases 10, or '!help listreleases' for more information.");
				int i = 1;
				while (sdr.Read())
				{
					user = sdr.GetString(0);
					date = sdr.GetString(1);
					time = sdr.GetString(2);
					category = sdr.IsDBNull(3) ? "N/A" : sdr.GetString(3);
					magnet = sdr.GetString(4);

					sb.AppendLine(String.Format("{0}: <{1}> [{2} - {3}] [{4}] - Magnet Link: {5}", i, user, date, time, category, magnet));

					i++;
				}
				this.ParentBot.SendEchoMessageFromBot(source, sb.ToString());
			}

			return true;
		}
	}
}
